<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
<div style="width: 100%;border:1px solid #f8f8f8;border-radius:5px;background: #f8f8f8">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="机构名称">
          <j-select-depart v-decorator="['office', validatorRules.office]"/>
          <!--            <a-input placeholder="请输入机构名称" v-decorator="[ 'office', validatorRules.office]" />-->
        </a-form-item>

        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="信息化负责人">
              <a-input placeholder="负责人"  v-decorator="[ 'principal', validatorRules.principal]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="联系电话">
              <a-input placeholder="联系电话"  v-decorator="[ 'principalPhone', validatorRules.principalPhone]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="邮箱">
              <a-input placeholder="邮箱"  v-decorator="[ 'principalMail', validatorRules.principalMail]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="联系人">
              <a-input placeholder="联系人"  v-decorator="[ 'linkman', validatorRules.linkman]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="联系电话">
              <a-input placeholder="联系电话"  v-decorator="[ 'linkmanPhone', validatorRules.linkmanPhone]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="邮箱">
              <a-input placeholder="邮箱"  v-decorator="[ 'linkmanMail', validatorRules.linkmanMail]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="主要用途">
              <a-input placeholder="主要用途"  v-decorator="[ 'mainUses', validatorRules.mainUses]" />
            </a-form-item>
          </a-col>
        </a-row>
</div>
        <br/><br/>
        <a-row :gutter="24">
          <div style="margin-left: 20px">服务器信息：</div>
        </a-row>
<div style="width: 100%;border:1px solid #f8f8f8;border-radius:5px;background: #f8f8f8">
        <br/>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="系统名称">
              <a-input placeholder="系统名称"  v-decorator="[ 'systemName', validatorRules.systemName]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-show="issetmeal">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="服务器">
              <j-dict-select-tag ref="meal" :triggerChange="true" placeholder="选择套餐" dictCode="jinan_server_expense,params,id,server_value &lt; 5" v-decorator="[ 'setMeal', {rules: [{ required: true, message: '请选择服务器!' }]}]" @change="mealChange"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="系统技术类型">
              <j-dict-select-tag :triggerChange="true" placeholder="请选择技术类型" dictCode="sys_technology_type" v-decorator="[ 'sysTechnologyType', validatorRules.sysTechnologyType]"/>
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="操作系统">
              <j-dict-select-tag :triggerChange="true" placeholder="请选择操作系统" dictCode="os" v-decorator="[ 'os', validatorRules.os]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <!--          <a-row :gutter="24">-->
        <!--            <a-form-item label="申请业务类型">-->
        <!--              <j-multi-select-tag-->
        <!--                dictCode="tos"-->
        <!--                type="checkbox"-->
        <!--                v-decorator="[ 'tos', validatorRules.tos]"-->
        <!--                :disabled="dis">-->
        <!--              </j-multi-select-tag>-->
        <!--            </a-form-item>-->
        <!--          </a-row>-->
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="内网ip">
              <a-input ref="intranetIps" placeholder="多个Ip逗号分隔"  v-decorator="[ 'intranetIp', validatorRules.ip]" @change="ipTransform"/>
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="外网ip">
              <a-input ref="outernetIps" placeholder="多个Ip逗号分隔"  v-decorator="[ 'outernetIp', validatorRules.ip]" @change="ipTransform"/>
            </a-form-item>
          </a-col>
        </a-row>
<!--        <a-row :gutter="24">-->
<!--          <a-form-item-->
<!--            :labelCol="labelRow"-->
<!--            :wrapperCol="wrapperRow"-->
<!--            label="">-->
<!--            <j-dict-select-tag ref="isType" v-decorator="['type', {}]" :type="'radio'" :triggerChange="true" dictCode="select_type" @change="changeType"/>-->
<!--          </a-form-item>-->
<!--        </a-row>-->
          <a-row :gutter="24" v-show="iscustom">
            <a-col :md="8">
              <a-form-item
                :labelCol="labelRow"
                :wrapperCol="wrapperRow"
                label="内存(G)">
                <a-input ref="memory" placeholder="内存"  v-decorator="[ 'memory', validatorRules.memory]" @blur="billing"/>
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <a-form-item
                :labelCol="labelRow"
                :wrapperCol="wrapperRow"
                label="磁盘(G)">
                <a-input ref="disk" placeholder="磁盘"  v-decorator="[ 'disk', validatorRules.disk]" @blur="billing"/>
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <a-form-item
                :labelCol="labelRow"
                :wrapperCol="wrapperRow"
                label="CPU">
                <j-dict-select-tag ref="cpu" :triggerChange="true" placeholder="请选择CPU" dictCode="cpu" v-decorator="[ 'cpu', validatorRules.cpu]" @change="cpuChange"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8">
              <a-form-item
                :labelCol="labelRow"
                :wrapperCol="wrapperRow"
                label="服务器数量">
                <a-input-number ref="num" :min="1" v-decorator="['serverNum',{'initialValue':1}]" @blur="billing"/>
              </a-form-item>
            </a-col>
          </a-row>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="数据库">
              <j-dict-select-tag ref="dataBase" :triggerChange="true" placeholder="选择数据库" dictCode="jinan_data_base,params,id" v-decorator="[ 'dataBase', validatorRules.dataBase]" @change="dataBaseChange"/>
            </a-form-item>
          </a-col>
        </a-row>
          <a-row :gutter="24">
            <a-col :md="8">
              <a-form-item
                :labelCol="labelRow"
                :wrapperCol="wrapperRow"
                label="开通时间">
                <j-date ref="openTime" v-decorator="[ 'openTime', validatorRules.openTime]" @change="dateChange"></j-date>
              </a-form-item>
            </a-col>
          </a-row>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item :labelCol="labelRow"
                         :wrapperCol="wrapperRow" label="开放端口">
              <j-multi-select-tag
                dictCode="ports"
                type="checkbox"
                v-decorator="[ 'openPorts', validatorRules.openPorts]"
                :disabled="dis">
              </j-multi-select-tag>
            </a-form-item>
          </a-col>
        </a-row>
<!--          <a-col :md="8">-->
<!--            <a-button type="primary"  @click="billing">计费</a-button>-->
<!--          </a-col>-->
</div>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="费用">
              <a-input ref="cost" placeholder="费用" disabled="disabled"  v-decorator="[ 'cost', validatorRules.cost]" />
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit" style="margin-top: 10px">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">返回</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
    import pick from 'lodash.pick'
    import {saveCloudList,editCloudList,annualPrice } from '@/api/api'
    import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
    import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
    import JDate from '@/components/jeecg/JDate'
    import {ajaxFilterDictText} from '@/components/dict/JDictSelectUtil'
    import {getAnnualPrice,getServerExpense1,getDataBaseName,getServerParam,myDate} from '@/utils/ipDate'
    export default {
        components: {
            JMultiSelectTag,
            JSelectDepart,
            JDate,
        },
        name: "cloudListEditModal",
        data(){
            return{
                form: this.$form.createForm(this),
                title:"操作",
                visible: false,
                iscustom:true,
                issetmeal:true,
                sumbit:false,
                model: {},
                labelCol: {
                    xs: { span: 24 },
                    sm: { span: 2 },
                },
                wrapperCol: {
                    xs: { span: 24 },
                    sm: { span: 16 },
                },
                labelRow: {
                    xs: { span: 12 },
                    sm: { span: 10 },
                },
                wrapperRow: {
                    xs: { span: 12 },
                    sm: { span: 14 },
                },
                dis:false,
                hiding:true,
                drawerWidth:1000,
                confirmLoading: false,
                disableSubmit:false,
                validatorRules:{
                    principalPhone:{rules: [{validator: this.validatePhone}]},
                    linkmanPhone:{rules: [{validator: this.validatePhone}]},
                    principalMail:{rules: [{validator: this.validateEmail}]},
                    linkmanMail:{rules: [{validator: this.validateEmail}]},
                    memory:{rules: [{validator: this.validateNum}]},
                    disk:{rules: [{validator: this.validateNum}]},
                    ip:{rules: [{validator: this.ipVerify}]}
                },
            }
        },
        methods:{
            ipTransform(e){
                var val = e.currentTarget
                if((val.value).indexOf("，")>-1){
                    val.value = (val.value).replace("，",",");
                }
                this.billing();
            },
          ipVerify(rule, value, callback){
            var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            if(!value){
              callback()
            }else{
              if(value.indexOf(",")>-1){
                value = value.replace("，",",");
                let val = value.split(",");
                let sign = 1;
                for(let i=0;i<val.length;i++){
                  if(!reg.test(val[i])){
                    sign++;
                    callback("IP地址不规范!")
                    break;
                  }
                }
                if(sign == 1){
                  callback()
                }
              }else{
                if(!reg.test(value)){
                  callback("IP地址不规范!")
                }else{
                  callback()
                }
              }
            }
          },
            mealChange(e){
                this.billing("1",e);
            },
            dataBaseChange(e){
                this.billing("2",e);
            },
            async cpuChange(e){
                let cpuValue = await ajaxFilterDictText("cpu",e);
                this.billing("3",cpuValue);
            },
            dateChange(e){
                this.billing("4",e);
            },
            async billing(type,e){
              let date = type=="4"?e:this.$refs.openTime.value==undefined?new Date().format("yyyy-MM-dd"):this.$refs.openTime.value;
              let sum = 0;
              let ipsValue = this.$refs.outernetIps.value;
              let dataBaseVal = type=="2"?e:this.$refs.dataBase.value;
              let mealId = type=="1"?e:this.$refs.meal.value;
              debugger;
              let num = this.$refs.num.value;
              // let type = this.$refs.isType.value;
              if(ipsValue!=undefined && ipsValue != '' && ipsValue != null){//ip费用
                  sum = parseFloat((sum + await getAnnualPrice(ipsValue.split(",").length,date)).toFixed(2));
              }
              // if(type=="0"){//服务器选择
              if(mealId!=undefined && mealId != '' && mealId != null){
                  sum = parseFloat((sum + await getServerExpense1(mealId,date)).toFixed(2));
              }
              // }else if(type=="1"){//自定义选择
                  //cpu、内存、硬盘计算费用
              var re1 = /(\d{1,3})+(?:\.\d+)?/g
              let cpu = parseInt(type=="3"?e.match(re1):this.$refs.cpu.$el.innerText.match(re1));
              let disk = parseInt(this.$refs.disk.value);
              let memory = parseInt(this.$refs.memory.value);
              sum = parseFloat((sum + await getServerParam(cpu,disk,memory,date)).toFixed(2));
              // }
              if(dataBaseVal != undefined && dataBaseVal != '' && dataBaseVal != null){//数据库费用
                  sum = parseFloat((sum + await getDataBaseName(dataBaseVal,date)).toFixed(2));
              }
              this.$refs.cost.$refs.input.value = sum*num;
                  // this.sumbit = true;
            },
            // changeType(e){
            //     if(e=="1"){
            //         this.issetmeal = false;//套餐
            //         this.iscustom = true;//自定义
            //     }else{
            //         this.iscustom = false;
            //         this.issetmeal = true;
            //     }
            // },
            validateNum(rule, value, callback){
                if(!value){
                    callback()
                }else{
                    if(new RegExp(/[^\d]/g).test(value)){
                        callback("请输入正确的数字!")
                    }else{
                        callback()
                    }
                }
            },
            validateEmail(rule, value, callback){
                if(!value){
                    callback()
                }else{
                    if(new RegExp(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/).test(value)){
                        callback()
                    }else{
                        callback("请输入正确格式的邮箱!")
                    }
                }
            },
            validatePhone(rule, value, callback){
                if(!value){
                    callback()
                }else{
                    if(new RegExp(/^1[3|4|5|7|8][0-9]\d{8}$/).test(value)){
                        callback()
                    }else{
                        callback("请输入正确格式的手机号码!");
                    }
                }
            },
            close () {
                this.$emit('close');
                this.visible = false;
                this.disableSubmit = false;
            },
            add () {
                this.edit();
                // this.edit({type:'0'});
            },
            edit(record){
                // this.changeType(record.type);
                this.form.resetFields();
                this.model = Object.assign({}, record);
                this.visible = true;
                this.$nextTick(() => {
                    this.form.setFieldsValue(pick(this.model,'office', 'principal','principalPhone','principalMail','linkman','linkmanPhone'
                        ,'linkmanMail','systemName','mainUses','intranetIp','outernetIp',/*'tos',*/'serverNum','dataBase','sysTechnologyType',
                        'os','memory','disk','cpu','openPorts','createTime','setMeal','openTime','lastSettlementTime','cost'))
                });
            },
            handleCancel () {
                this.close()
            },
            // eitdData(formData){
            //     if(formData.type=="0"){//套餐类型
            //         formData.cpu = "";
            //         formData.memory = "";
            //         formData.disk = "";
            //     }else{//自定义类型
            //         formData.setMeal="";
            //     }
            // },
            handleSubmit () {
                const that = this;
                let type={type:'1'};
                var price = this.$refs.cost.$refs.input.value;
                // if(this.sumbit){
                    // 触发表单验证
                    this.form.validateFields((err, values) => {
                        if (!err) {
                            that.confirmLoading = true;
                            let formData = Object.assign(this.model, values,type);
                            formData.cost = price;
                            let obj;
                            // this.eitdData(formData);
                                obj=saveCloudList(formData);
                            // if(!this.model.id){
                            // }else{
                            //     obj=editCloudList(formData);
                            // }
                            obj.then((res)=>{
                                if(res.success){
                                    that.$message.success(res.message);
                                    that.$emit('ok');
                                }else{
                                    that.$message.warning(res.message);
                                }
                            }).finally(() => {
                                that.confirmLoading = false;

                                that.close();
                            })

                        }
                    })
                // }else{
                //     that.$message.warning("请重新计费后提交");
                // }
            },
        }
    }

    Date.prototype.format = function(fmt) {
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    }
</script>

<style scoped>

</style>